package middleware

import (
	"kstar-gf-api/app/admin/api"
	"kstar-gf-api/library/redislock"
	"kstar-gf-api/library/response"

	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
)

// 校验登录
func MiddlewareAdminLoginHandler(r *ghttp.Request) {

	sessionInfo, _ := r.Session.Data()

	var userInfo *api.UserInfo
	if err := gconv.Struct(sessionInfo, &userInfo); err != nil {
		response.NotLoginReturn(r)
	}

	if userInfo.UserId == "" {
		response.NotLoginReturn(r)
	}

	//设置上下文变量
	r.SetCtxVar("tokenId", userInfo.TokenId)
	r.SetCtxVar("userId", userInfo.UserId)
	r.SetCtxVar("userName", userInfo.UserName)
	r.SetCtxVar("userPhone", userInfo.UserPhone)
	r.SetCtxVar("CreateBy", userInfo.CreateBy)

	// post接口防止重复提交数据，必须等上一次返回后才能调下一次
	if r.Method == "POST" {
		ctx := r.Request.Context()

		// 根据URL+userId生成唯一的Redis锁key
		urlPath := r.URL.Path
		lockKey := "PostLock:" + urlPath + ":" + userInfo.UserId

		// 尝试获取锁，如果获取失败说明重复调用post请求
		lockAcquired := redislock.AcquireLock(ctx, lockKey)
		if !lockAcquired {
			response.InnerErrorReturn(r, gerror.New("post请求调用太频繁"))
		}

		// 确保在请求结束时释放锁
		defer redislock.ReleaseLock(ctx, lockKey)
	}

	r.Middleware.Next()
}

// 校验登录学校
func MiddlewareAdminLoginSchoolHandler(r *ghttp.Request) {

	sessionInfo, _ := r.Session.Data()

	var userInfo *api.UserInfo
	if err := gconv.Struct(sessionInfo, &userInfo); err != nil {
		response.NotLoginReturn(r)
	}

	if userInfo.UserId == "" {
		response.NotLoginReturn(r)
	}

	if userInfo.TenantId == "" {
		response.NotLoginReturn(r)
	}

	//设置上下文变量
	r.SetCtxVar("tenantId", userInfo.TenantId)
	r.SetCtxVar("tenantName", userInfo.TenantName)
	r.SetCtxVar("roleIds", userInfo.RoleIds)
	r.SetCtxVar("roleNames", userInfo.RoleNames)

	r.Middleware.Next()
}
